package com.smw.util;

import com.smw.entity.User;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class SendHttp {
    /**
     * 构建带参数的post请求
     * @param url
     */
    private User user;
    public static void doPost(String url){
        CloseableHttpClient httpClient=null;
        CloseableHttpResponse httpResponse=null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().build();
            httpPost.setConfig(config);

            //请求参数设置环节
            //2:创建list,满足1的需求
            List<NameValuePair> lists=new ArrayList<NameValuePair>();
            //3:往2中的list添加参数信息
            lists.add(new BasicNameValuePair("email","2968698432"));
            //1：往请求对象中塞入请求参数，setEntity()方法
            //使用实现类：UrlEncodedFormEntity,需要一个list,给定list
            httpPost.setEntity(new UrlEncodedFormEntity(lists));

            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            System.out.println("--------------"+httpEntity);
            String result= EntityUtils.toString(httpEntity);
        }catch (Exception e){

        }
    }
//    public static void doPost(String url){
//        CloseableHttpClient httpClient=null;
//        CloseableHttpResponse httpResponse=null;
//        try {
//            httpClient = HttpClients.createDefault();
//            HttpPost httpPost = new HttpPost(url);
//            RequestConfig config = RequestConfig.custom().build();
//            httpPost.setConfig(config);
//            httpResponse = httpClient.execute(httpPost);
//            HttpEntity httpEntity=httpResponse.getEntity();
//            System.out.println("--------------"+httpEntity);
//            String result= EntityUtils.toString(httpEntity);
//            System.out.println("---"+result);
//        }catch (Exception e){
//e.printStackTrace();
//        }
//    }
//    public static void main(String[] args) {
//        doPost("http://localhost:8080/ni/Hao");
//    }
}
